using Godot;
using System;
using System.Collections.Generic;
using System.Runtime;

public partial class ViewManager
{
	private static ViewManager _instance = null;

	public Node viewRootNode { get; set; }
	public static ViewManager getInstance()
	{
		if (_instance is null)
		{
			_instance = new ViewManager();
		}
		return _instance;
	}

	public void open(string viewName, Dictionary<string, object> param = null)
	{

		var isHasView = viewRootNode.HasNode(viewName);

		ViewConfig.viewDict.TryGetValue(viewName, out var config);
		if (isHasView)
		{
			var view = viewRootNode.GetNode<WindowBase>(viewName);
			if (config.isResidentView)  //是否常驻页面 (这里是直接执行onshow，没有销毁)
			{
				view.Visible = true;
				view.onShow();
			}


		}
		else
		{
			var view = (WindowBase)ResourceLoader.Load<PackedScene>("res://view/" + viewName + ".tscn").Instantiate();  //加载页面实例
			viewRootNode.AddChild(view);
			view.viewName = viewName;
			if (param is not null)
			{
				view.viewParamDict = param;
			}
			view.init();
			view.onShow();

		}


		/*if (config.isCloseOthers) //是否关闭其他
		{
			foreach (var child in viewRootNode.GetChildren())
			{
				ViewConfig.viewDict.TryGetValue(child.Name, out var childConfig);
				if (childConfig is not null)
				{
					if (!childConfig.isResidentView)  //非常驻页面
					{
						viewRootNode.RemoveChild(child);
						child.Free();
					}
				}


			}
		}*/

	}

	public bool isOpen(string viewName)
	{
		var view = viewRootNode.GetNodeOrNull<WindowBase>(viewName);
		if (view is not null)
		{
			return view.Visible;
		}
		else
		{
			return false;
		}
	}

	public void close(string viewName, Action callFunc = null)
	{

		ViewConfig.viewDict.TryGetValue(viewName, out var config);



		var view = viewRootNode.GetNode<WindowBase>(viewName);
		if (config is not null)
		{
			if (config is not null || config.isResidentView)
			{
				view.hide();
			}
			else
			{
				viewRootNode.RemoveChild(view);
				if (view is not null)
				{
					view.destroy();
				}

			}
		}
		else
		{

			viewRootNode.RemoveChild(view);
			if (view is not null)
			{
				view.destroy();
			}


		}

		if (callFunc != null)
		{
			callFunc();
		}



	}

}



